<template>
  <!-- 移动端菜单按钮 -->
  <div class="mobile-menu-button" v-if="isMobile" @click="toggleCollapse">
    <el-icon><MenuIcon /></el-icon>
  </div>

  <div class="sidebar" :class="{ 
    'collapsed': isCollapsed && !isMobile, 
    'mobile': isMobile,
    'visible': isMobileVisible && isMobile
  }">
    <div class="sidebar-header">
      <div class="logo-container">
        <el-icon class="logo-icon"><Document /></el-icon>
        <span class="logo-text important-feature" v-show="!isCollapsed || (isMobile && isMobileVisible)">cr文档管理系统</span>
      </div>
      <el-icon 
        class="collapse-icon"
        @click="toggleCollapse"
      >
        <component :is="isCollapsed && !isMobile ? 'Expand' : 'Fold'" />
      </el-icon>
    </div>

    <el-scrollbar>
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu"
        :collapse="isCollapsed && !isMobile"
        :collapse-transition="false"
        @select="handleSelect"
      >
        <el-menu-item index="/dashboard">
          <el-icon><HomeFilled /></el-icon>
          <template #title>
            <span class="important-feature">首页</span>
          </template>
        </el-menu-item>

        <!-- 新增：最近访问 -->
        <el-sub-menu index="recent">
          <template #title>
            <el-icon><Clock /></el-icon>
            <span class="important-feature">最近访问</span>
          </template>
          <div class="recent-items-container" v-if="recentItems.length > 0">
            <el-menu-item 
              v-for="(item, index) in recentItems" 
              :key="index" 
              :index="item.path"
            >
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.title }}</span>
            </el-menu-item>
          </div>
          <el-menu-item v-else index="no-recent" disabled>
            <span>暂无最近访问记录</span>
          </el-menu-item>
          <el-menu-item index="action:clear-recent" @click="clearRecentItems">
            <el-icon><Delete /></el-icon>
            <span>清除历史记录</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 新增：收藏夹 -->
        <el-sub-menu index="favorites">
          <template #title>
            <el-icon><Star /></el-icon>
            <span class="important-feature">收藏夹</span>
            <el-badge v-if="favoriteItems.length > 0" :value="favoriteItems.length" :max="99" class="favorite-badge" />
          </template>
          <div class="favorite-items-container" v-if="favoriteItems.length > 0">
            <el-menu-item 
              v-for="(item, index) in favoriteItems" 
              :key="index" 
              :index="item.path"
            >
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.title }}</span>
              <el-icon class="remove-favorite" @click.stop="removeFavorite(index)"><Close /></el-icon>
            </el-menu-item>
          </div>
          <el-menu-item v-else index="no-favorites" disabled>
            <span>暂无收藏项目</span>
          </el-menu-item>
          <el-menu-item index="action:manage-favorites" @click="showFavoriteManager = true">
            <el-icon><Setting /></el-icon>
            <span>管理收藏夹</span>
          </el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="1">
          <template #title>
            <el-icon><Document /></el-icon>
            <span class="important-feature">文档管理</span>
          </template>
          <el-menu-item index="/dashboard/documents"><span>全部文档</span></el-menu-item>
          <el-menu-item index="/dashboard/upload"><span>上传文档</span></el-menu-item>
          <el-menu-item index="/dashboard/parser"><span>文档解析</span></el-menu-item>
          <el-menu-item index="/dashboard/shared"><span>共享文档</span></el-menu-item>
          
          <!-- 添加文档解析快捷入口 -->
          <el-divider content-position="center">解析工具</el-divider>
          <el-menu-item index="/dashboard/parser/document-list" class="featured-parser">
            <el-icon><Document /></el-icon>
            <span>文档列表</span>
          </el-menu-item>
          <el-menu-item index="/dashboard/parser/questions" class="featured-parser">
            <el-icon><QuestionFilled /></el-icon>
            <span>解析问题</span>
          </el-menu-item>
          <el-menu-item index="/dashboard/parser/import" class="featured-parser">
            <el-icon><Download /></el-icon>
            <span>导入练习</span>
          </el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="3">
          <template #title>
            <el-icon><Reading /></el-icon>
            <span class="important-feature">练习题系统</span>
          </template>
          <el-menu-item index="/dashboard/exercises"><span>练习集列表</span></el-menu-item>
          <!-- 增强练习题系统子菜单 -->
          <el-menu-item index="/dashboard/exercises/my-exercises"><span>我的练习</span></el-menu-item>
          <el-menu-item index="/dashboard/exercises/recent"><span>最近练习</span></el-menu-item>
          <el-menu-item index="/dashboard/exercises/statistics"><span>练习统计</span></el-menu-item>
          <el-menu-item index="/dashboard/exercises/create"><span>创建练习集</span></el-menu-item>
          <el-menu-item index="/dashboard/exercises/simple-create"><span>快速创建练习</span></el-menu-item>
          
          <!-- 添加练习快捷入口 -->
          <el-divider content-position="center">快捷练习</el-divider>
          
          <!-- 添加练习ID 25的直接链接 -->
          <el-menu-item index="/dashboard/exercises/25/practice" class="featured-exercise">
            <el-icon><Star /></el-icon>
            <span>推荐练习集 #25</span>
            <el-tag size="small" type="success" class="featured-tag">热门</el-tag>
          </el-menu-item>
          
          <div v-if="isLoadingExercises" class="loading-exercises">
            <el-skeleton style="padding: 8px 20px;" :rows="3" animated />
          </div>
          <div v-else-if="recentExercises.length > 0">
            <el-menu-item 
              v-for="exercise in recentExercises" 
              :key="exercise.id" 
              :index="`/dashboard/exercises/${exercise.id}/practice`"
              class="recent-exercise-item"
            >
              <el-icon><Reading /></el-icon>
              <span class="recent-exercise-title">{{ exercise.title }}</span>
              <el-tag size="small" class="recent-exercise-count">{{ exercise.exercises?.length || exercise.questions?.length || 0 }}题</el-tag>
            </el-menu-item>
            <el-menu-item index="/dashboard/exercises/recent">
              <el-icon><More /></el-icon>
              <span>查看更多练习</span>
            </el-menu-item>
          </div>
          <el-menu-item v-else index="no-recent-exercises" disabled>
            <span>暂无最近练习</span>
          </el-menu-item>
          
          <!-- 添加练习模式选择 -->
          <el-divider content-position="center">练习模式</el-divider>
          <el-menu-item index="/dashboard/exercises/mode/standard" class="exercise-mode-item">
            <el-icon><Reading /></el-icon>
            <span>标准模式</span>
          </el-menu-item>
          <el-menu-item index="/dashboard/exercises/mode/exam" class="exercise-mode-item">
            <el-icon><Timer /></el-icon>
            <span>考试模式</span>
            <el-tag size="small" type="warning" class="mode-tag">计时</el-tag>
          </el-menu-item>
          <el-menu-item index="/dashboard/exercises/mode/challenge" class="exercise-mode-item">
            <el-icon><Trophy /></el-icon>
            <span>挑战模式</span>
            <el-tag size="small" type="danger" class="mode-tag">难度+</el-tag>
          </el-menu-item>
        </el-sub-menu>

        <!-- 新增：快捷工具 -->
        <el-sub-menu index="tools">
          <template #title>
            <el-icon><Tools /></el-icon>
            <span class="important-feature">快捷工具</span>
          </template>
          <el-menu-item index="action:search-all" @click="showGlobalSearch = true">
            <el-icon><Search /></el-icon>
            <span>全局搜索</span>
          </el-menu-item>
          <el-menu-item index="/dashboard/question-parser">
            <el-icon><Reading /></el-icon>
            <span>题目解析器</span>
          </el-menu-item>
          <el-menu-item index="action:export-data" @click="showExportDialog = true">
            <el-icon><Download /></el-icon>
            <span>数据导出</span>
          </el-menu-item>
          <el-menu-item index="action:import-data" @click="showImportDialog = true">
            <el-icon><Upload /></el-icon>
            <span>数据导入</span>
          </el-menu-item>
          <el-menu-item index="action:refresh-data" @click="refreshAllData">
            <el-icon><Refresh /></el-icon>
            <span>刷新数据</span>
          </el-menu-item>
        </el-sub-menu>

        <el-menu-item index="/dashboard/notifications">
          <el-icon><Bell /></el-icon>
          <template #title>
            <span class="important-feature">通知中心</span>
            <el-badge 
              v-if="unreadCount > 0" 
              :value="unreadCount" 
              :max="99"
              class="notification-badge"
            />
          </template>
        </el-menu-item>

        <el-sub-menu index="2">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span class="important-feature">系统设置</span>
          </template>
          <el-menu-item index="/dashboard/profile"><span>个人信息</span></el-menu-item>
          <el-menu-item index="/dashboard/settings"><span>系统设置</span></el-menu-item>
          <el-menu-item index="action:background-settings" @click="showBackgroundSettings = true"><span>背景设置</span></el-menu-item>
          <el-menu-item index="action:cursor-settings" @click="showCursorSettings = true"><span>光标设置</span></el-menu-item>
          <el-menu-item index="/dashboard/background-test" v-if="isDevelopment"><span>背景设置测试</span></el-menu-item>
        </el-sub-menu>

        <el-menu-item index="/dashboard/about">
          <el-icon><InfoFilled /></el-icon>
          <template #title><span class="important-feature">关于系统</span></template>
        </el-menu-item>
      </el-menu>
    </el-scrollbar>

    <div class="sidebar-footer" @click="handleLogout">
      <el-icon><SwitchButton /></el-icon>
      <span class="important-feature" v-show="!isCollapsed || (isMobile && isMobileVisible)">退出登录</span>
    </div>
  </div>

  <!-- 背景设置面板 -->
  <BackgroundSettings 
    v-model="showBackgroundSettings"
    @settings-updated="handleBackgroundSettingsUpdated"
  />

  <!-- 光标设置面板 -->
  <el-drawer
    v-model="showCursorSettings"
    title="光标设置"
    direction="rtl"
    size="350px"
    :with-header="true"
    :destroy-on-close="false"
    :modal="true"
    :show-close="true"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
  >
    <div class="cursor-settings-content">
      <!-- 光标颜色设置 -->
      <div class="setting-group">
        <div class="setting-label">光标颜色</div>
        <el-color-picker v-model="cursorColor" show-alpha></el-color-picker>
      </div>
      
      <!-- 光标大小设置 -->
      <div class="setting-group">
        <div class="setting-label">光标大小: {{ cursorSize }}</div>
        <el-slider v-model="cursorSize" :min="0.5" :max="2" :step="0.1"></el-slider>
      </div>
      
      <!-- 预设光标颜色 -->
      <div class="setting-group">
        <div class="setting-label">预设颜色</div>
        <div class="preset-colors">
          <div 
            v-for="(color, index) in presetCursorColors" 
            :key="index" 
            class="preset-color" 
            :style="{ backgroundColor: color }"
            :class="{ active: cursorColor === color }"
            @click="cursorColor = color"
          ></div>
        </div>
      </div>
      
      <!-- 保存设置 -->
      <div class="setting-actions">
        <el-button type="primary" @click="saveCursorSettings">保存设置</el-button>
        <el-button @click="resetCursorSettings">重置</el-button>
      </div>
    </div>
  </el-drawer>

  <!-- 收藏夹管理器 -->
  <el-drawer
    v-model="showFavoriteManager"
    title="收藏夹管理"
    direction="rtl"
    size="400px"
    :with-header="true"
    :destroy-on-close="false"
    :modal="true"
    :show-close="true"
  >
    <div class="favorite-manager-content">
      <div class="favorite-manager-header">
        <h3>我的收藏</h3>
        <el-button type="primary" size="small" @click="showAddFavoriteForm = true">
          <el-icon><Plus /></el-icon>添加收藏
        </el-button>
      </div>

      <el-empty v-if="favoriteItems.length === 0" description="暂无收藏项目" />

      <el-table v-else :data="favoriteItems" style="width: 100%" border>
        <el-table-column prop="title" label="名称" min-width="120" />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getFavoriteTypeTag(row.icon)">
              {{ getFavoriteTypeText(row.icon) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ $index }">
            <el-button-group>
              <el-button type="primary" size="small" @click="editFavorite($index)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button type="danger" size="small" @click="removeFavorite($index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加收藏表单 -->
      <el-dialog
        v-model="showAddFavoriteForm"
        title="添加收藏"
        width="400px"
        custom-class="custom-dialog"
      >
        <el-form :model="newFavorite" label-width="80px">
          <el-form-item label="名称" required>
            <el-input v-model="newFavorite.title" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="路径" required>
            <el-input v-model="newFavorite.path" placeholder="请输入路径" />
          </el-form-item>
          <el-form-item label="图标">
            <el-select v-model="newFavorite.icon" placeholder="请选择图标">
              <el-option label="文档" value="Document" />
              <el-option label="练习" value="Reading" />
              <el-option label="设置" value="Setting" />
              <el-option label="用户" value="User" />
              <el-option label="工具" value="Tools" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddFavoriteForm = false">取消</el-button>
          <el-button type="primary" @click="addFavorite">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </el-drawer>

  <!-- 全局搜索对话框 -->
  <el-dialog
    v-model="showGlobalSearch"
    title="全局搜索"
    width="600px"
    :destroy-on-close="false"
    custom-class="custom-dialog"
  >
    <div class="global-search-content">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入搜索关键词"
        prefix-icon="Search"
        clearable
        @keyup.enter="performSearch"
      >
        <template #append>
          <el-button @click="performSearch">搜索</el-button>
        </template>
      </el-input>

      <div class="search-options">
        <el-checkbox-group v-model="searchOptions">
          <el-checkbox label="documents">文档</el-checkbox>
          <el-checkbox label="exercises">练习题</el-checkbox>
          <el-checkbox label="notes">笔记</el-checkbox>
          <el-checkbox label="users">用户</el-checkbox>
        </el-checkbox-group>
      </div>

      <div class="search-results" v-if="searchResults.length > 0">
        <h3>搜索结果</h3>
        <el-tabs v-model="activeSearchTab">
          <el-tab-pane label="全部" name="all">
            <el-list>
              <el-list-item v-for="(result, index) in searchResults" :key="index">
                <div class="search-result-item" @click="navigateToResult(result)">
                  <el-icon><component :is="getResultIcon(result.type)" /></el-icon>
                  <div class="result-info">
                    <div class="result-title">{{ result.title }}</div>
                    <div class="result-description">{{ result.description }}</div>
                  </div>
                  <el-tag size="small">{{ getResultTypeText(result.type) }}</el-tag>
                </div>
              </el-list-item>
            </el-list>
          </el-tab-pane>
          <el-tab-pane label="文档" name="documents" v-if="hasResultType('documents')">
            <el-list>
              <el-list-item v-for="(result, index) in getResultsByType('documents')" :key="index">
                <div class="search-result-item" @click="navigateToResult(result)">
                  <el-icon><Document /></el-icon>
                  <div class="result-info">
                    <div class="result-title">{{ result.title }}</div>
                    <div class="result-description">{{ result.description }}</div>
                  </div>
                </div>
              </el-list-item>
            </el-list>
          </el-tab-pane>
          <el-tab-pane label="练习题" name="exercises" v-if="hasResultType('exercises')">
            <el-list>
              <el-list-item v-for="(result, index) in getResultsByType('exercises')" :key="index">
                <div class="search-result-item" @click="navigateToResult(result)">
                  <el-icon><Reading /></el-icon>
                  <div class="result-info">
                    <div class="result-title">{{ result.title }}</div>
                    <div class="result-description">{{ result.description }}</div>
                  </div>
                </div>
              </el-list-item>
            </el-list>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-empty v-else-if="hasSearched" description="未找到匹配的结果" />
    </div>
  </el-dialog>

  <!-- 数据导出对话框 -->
  <el-dialog
    v-model="showExportDialog"
    title="数据导出"
    width="500px"
    custom-class="custom-dialog"
  >
    <div class="export-dialog-content">
      <h3>选择要导出的数据</h3>
      <el-checkbox-group v-model="exportOptions">
        <div class="export-option-item">
          <el-checkbox label="documents">文档数据</el-checkbox>
          <el-tooltip content="导出所有文档及其元数据" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
        <div class="export-option-item">
          <el-checkbox label="exercises">练习题数据</el-checkbox>
          <el-tooltip content="导出所有练习集和练习题" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
        <div class="export-option-item">
          <el-checkbox label="notes">笔记数据</el-checkbox>
          <el-tooltip content="导出所有笔记和标注" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
        <div class="export-option-item">
          <el-checkbox label="settings">系统设置</el-checkbox>
          <el-tooltip content="导出个人设置和偏好" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
      </el-checkbox-group>

      <div class="export-format">
        <h3>导出格式</h3>
        <el-radio-group v-model="exportFormat">
          <el-radio value="json" label="JSON"></el-radio>
          <el-radio value="csv" label="CSV"></el-radio>
          <el-radio value="excel" label="Excel"></el-radio>
        </el-radio-group>
      </div>
    </div>
    <template #footer>
      <el-button @click="showExportDialog = false">取消</el-button>
      <el-button type="primary" @click="exportData" :disabled="exportOptions.length === 0">
        开始导出
      </el-button>
    </template>
  </el-dialog>

  <!-- 数据导入对话框 -->
  <el-dialog
    v-model="showImportDialog"
    title="数据导入"
    width="500px"
    custom-class="custom-dialog"
  >
    <div class="import-dialog-content">
      <h3>选择要导入的数据类型</h3>
      <el-radio-group v-model="importType">
        <div class="import-option-item">
          <el-radio value="documents" label="文档数据"></el-radio>
          <el-tooltip content="导入文档及其元数据" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
        <div class="import-option-item">
          <el-radio value="exercises" label="练习题数据"></el-radio>
          <el-tooltip content="导入练习集和练习题" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
        <div class="import-option-item">
          <el-radio value="notes" label="笔记数据"></el-radio>
          <el-tooltip content="导入笔记和标注" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
        <div class="import-option-item">
          <el-radio value="settings" label="系统设置"></el-radio>
          <el-tooltip content="导入个人设置和偏好" placement="right">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
      </el-radio-group>

      <div class="file-upload-section">
        <h3>上传文件</h3>
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleImportFileChange"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              支持 .json, .csv, .xlsx 格式文件
            </div>
          </template>
        </el-upload>
      </div>
    </div>
    <template #footer>
      <el-button @click="showImportDialog = false">取消</el-button>
      <el-button type="primary" @click="importData" :disabled="!importFile">
        开始导入
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  Document,
  HomeFilled,
  Setting,
  User,
  Tools,
  InfoFilled,
  List,
  Upload,
  Share,
  Expand,
  Fold,
  SwitchButton,
  Bell,
  Reading,
  Menu as MenuIcon,
  Brush,
  Clock,
  Star,
  Delete,
  Close,
  Search,
  Download,
  Refresh,
  Plus,
  Edit,
  UploadFilled,
  More,
  QuestionFilled,
  Timer,
  Trophy
} from '@element-plus/icons-vue'
import axios from '../../utils/axios'
import BackgroundSettings from './BackgroundSettings.vue'

const router = useRouter()
const route = useRoute()
const props = defineProps({
  // ... existing props ...
})

const emit = defineEmits(['collapse-change'])

// 定义响应式变量
const showBackgroundSettings = ref(false)
const showCursorSettings = ref(false)
const isCollapsed = ref(false)
const isMobileVisible = ref(false)
const activeMenu = computed(() => route.path)
const refreshIntervalId = ref(null)

// 最近练习数据
const recentExercises = ref([])
const isLoadingExercises = ref(false)

// 获取最近练习
const fetchRecentExercises = async () => {
  if (!localStorage.getItem('access_token')) return
  
  isLoadingExercises.value = true
  try {
    // 获取用户最近练习的练习集
    const response = await axios.get('/exercises/progress/current/')
    
    if (Array.isArray(response.data) && response.data.length > 0) {
      // 按最后更新时间排序
      const sortedProgress = [...response.data].sort((a, b) => {
        return new Date(b.updated_at) - new Date(a.updated_at)
      })
      
      // 获取练习集详情
      const exerciseSetIds = sortedProgress.map(progress => progress.exercise_set)
      const uniqueIds = [...new Set(exerciseSetIds)].slice(0, 5) // 最多显示5个
      
      const exerciseSets = []
      for (const id of uniqueIds) {
        try {
          const exerciseResponse = await axios.get(`/exercises/exercise-sets/${id}/`)
          if (exerciseResponse.data && exerciseResponse.data.id) {
            // 确保有题目
            if ((exerciseResponse.data.exercises && exerciseResponse.data.exercises.length > 0) || 
                (exerciseResponse.data.questions && exerciseResponse.data.questions.length > 0)) {
              exerciseSets.push(exerciseResponse.data)
            }
          }
        } catch (error) {
          console.error(`获取练习集 ${id} 详情失败:`, error)
        }
      }
      
      recentExercises.value = exerciseSets
      console.log('最近练习集:', recentExercises.value)
    } else {
      recentExercises.value = []
    }
  } catch (error) {
    console.error('获取最近练习失败:', error)
    recentExercises.value = []
  } finally {
    isLoadingExercises.value = false
  }
}

// 检测是否为移动设备
const isMobile = computed(() => {
  return window.innerWidth <= 768
})

// 监听窗口大小变化
watch(
  () => isMobile.value,
  (newValue) => {
    if (!newValue) {
      isMobileVisible.value = false
    }
  }
)

// 监听折叠状态变化
watch(
  () => isCollapsed.value,
  (newValue) => {
    emit('collapse-change', newValue)
  }
)

// 监听移动端可见性变化
watch(
  () => isMobileVisible.value,
  (newValue) => {
    emit('collapse-change', !newValue)
  }
)

// 监听背景设置面板状态
watch(
  () => showBackgroundSettings.value,
  (newValue) => {
    console.log('背景设置面板状态变化:', newValue ? '打开' : '关闭')
    if (newValue) {
      // 面板打开时加载设置
      loadSettings()
    }
  }
)

// 监听光标设置面板状态
watch(
  () => showCursorSettings.value,
  (newValue) => {
    console.log('光标设置面板状态变化:', newValue ? '打开' : '关闭')
    if (newValue) {
      // 面板打开时加载设置
      loadCursorSettings()
    }
  }
)

// 模拟未读通知数量
const unreadCount = ref(3)

// 最近访问记录
const recentItems = ref([
  { title: '文档解析', path: '/dashboard/parser', icon: 'Document' },
  { title: '练习集：基础知识', path: '/dashboard/exercises/1', icon: 'Reading' },
  { title: '系统设置', path: '/dashboard/settings', icon: 'Setting' },
])

// 清除最近访问记录
const clearRecentItems = () => {
  ElMessageBox.confirm(
    '确定要清除所有最近访问记录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    recentItems.value = []
    ElMessage.success('已清除所有最近访问记录')
  }).catch(() => {})
}

// 收藏夹
const favoriteItems = ref([
  { title: '常用文档', path: '/dashboard/documents?tag=常用', icon: 'Document' },
  { title: '重要练习集', path: '/dashboard/exercises/2', icon: 'Reading' },
])

// 收藏夹管理器显示状态
const showFavoriteManager = ref(false)

// 添加收藏表单显示状态
const showAddFavoriteForm = ref(false)

// 新收藏项
const newFavorite = ref({
  title: '',
  path: '',
  icon: 'Document'
})

// 编辑收藏项
const editFavorite = (index) => {
  const item = favoriteItems.value[index]
  newFavorite.value = { ...item }
  showAddFavoriteForm.value = true
}

// 添加收藏项
const addFavorite = () => {
  if (!newFavorite.value.title || !newFavorite.value.path) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  // 检查是否已存在相同路径的收藏
  const existingIndex = favoriteItems.value.findIndex(item => item.path === newFavorite.value.path)
  
  if (existingIndex !== -1) {
    // 更新现有收藏
    favoriteItems.value[existingIndex] = { ...newFavorite.value }
    ElMessage.success('收藏项已更新')
  } else {
    // 添加新收藏
    favoriteItems.value.push({ ...newFavorite.value })
    ElMessage.success('收藏项已添加')
  }
  
  // 重置表单并关闭
  newFavorite.value = {
    title: '',
    path: '',
    icon: 'Document'
  }
  showAddFavoriteForm.value = false
}

// 获取收藏类型标签
const getFavoriteTypeTag = (icon) => {
  const types = {
    'Document': 'primary',
    'Reading': 'success',
    'Setting': 'info',
    'User': 'warning',
    'Tools': 'danger'
  }
  return types[icon] || 'info'
}

// 获取收藏类型文本
const getFavoriteTypeText = (icon) => {
  const types = {
    'Document': '文档',
    'Reading': '练习',
    'Setting': '设置',
    'User': '用户',
    'Tools': '工具'
  }
  return types[icon] || '其他'
}

// 全局搜索相关
const searchKeyword = ref('')
const searchOptions = ref(['documents', 'exercises', 'notes', 'users'])
const searchResults = ref([])
const activeSearchTab = ref('all')
const hasSearched = ref(false)

// 执行搜索
const performSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  // 模拟搜索结果
  searchResults.value = [
    { 
      id: 1, 
      type: 'documents', 
      title: '示例文档1', 
      description: '这是一个包含搜索关键词的文档', 
      path: '/dashboard/documents/1' 
    },
    { 
      id: 2, 
      type: 'exercises', 
      title: '练习集：基础知识', 
      description: '包含多道练习题的集合', 
      path: '/dashboard/exercises/1' 
    },
    { 
      id: 3, 
      type: 'documents', 
      title: '示例文档2', 
      description: '另一个相关文档', 
      path: '/dashboard/documents/2' 
    }
  ]
  
  hasSearched.value = true
}

// 导航到搜索结果
const navigateToResult = (result) => {
  router.push(result.path)
  showGlobalSearch.value = false
}

// 获取结果图标
const getResultIcon = (type) => {
  const icons = {
    'documents': 'Document',
    'exercises': 'Reading',
    'notes': 'Edit',
    'users': 'User'
  }
  return icons[type] || 'Document'
}

// 获取结果类型文本
const getResultTypeText = (type) => {
  const texts = {
    'documents': '文档',
    'exercises': '练习',
    'notes': '笔记',
    'users': '用户'
  }
  return texts[type] || '其他'
}

// 检查是否有特定类型的结果
const hasResultType = (type) => {
  return searchResults.value.some(result => result.type === type)
}

// 获取特定类型的结果
const getResultsByType = (type) => {
  return searchResults.value.filter(result => result.type === type)
}

// 数据导出相关
const exportOptions = ref([])
const exportFormat = ref('json')

// 导出数据
const exportData = () => {
  if (exportOptions.value.length === 0) {
    ElMessage.warning('请选择要导出的数据')
    return
  }
  
  ElMessage.success(`正在导出 ${exportOptions.value.join(', ')} 数据，格式为 ${exportFormat.value}`)
  
  // 模拟导出过程
  setTimeout(() => {
    ElMessage.success('数据导出成功')
    showExportDialog.value = false
  }, 1500)
}

// 数据导入相关
const importType = ref('documents')
const importFile = ref(null)

// 处理导入文件变化
const handleImportFileChange = (file) => {
  importFile.value = file
}

// 导入数据
const importData = () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  ElMessage.success(`正在导入 ${importType.value} 数据`)
  
  // 模拟导入过程
  setTimeout(() => {
    ElMessage.success('数据导入成功')
    showImportDialog.value = false
  }, 1500)
}

// 移除收藏项
const removeFavorite = (index) => {
  ElMessageBox.confirm(
    '确定要移除此收藏项吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    favoriteItems.value.splice(index, 1)
    ElMessage.success('已移除收藏项')
  }).catch(() => {})
}

// 全局搜索显示状态
const showGlobalSearch = ref(false)

// 导出对话框显示状态
const showExportDialog = ref(false)

// 导入对话框显示状态
const showImportDialog = ref(false)

// 刷新所有数据
const refreshAllData = () => {
  ElMessage.success('正在刷新数据...')
  // 这里可以添加实际的刷新逻辑
  setTimeout(() => {
    ElMessage.success('数据刷新完成')
  }, 1000)
}

const toggleCollapse = () => {
  if (isMobile.value) {
    isMobileVisible.value = !isMobileVisible.value
  } else {
    isCollapsed.value = !isCollapsed.value
  }
}

const handleSelect = (path) => {
  router.push(path)
  // 在移动设备上点击菜单项后自动隐藏侧边栏
  if (isMobile.value) {
    isMobileVisible.value = false
  }
}

const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 清除所有登录相关的本地存储
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('username')
    
    // 强制刷新页面，确保所有组件状态重置
    router.push('/login').then(() => {
      // 使用setTimeout确保路由跳转完成后再刷新
      setTimeout(() => {
        window.location.reload()
      }, 100)
    })
    
    ElMessage.success('已成功退出登录')
  }).catch(() => {})
}

// 在组件挂载时添加窗口大小变化监听
onMounted(() => {
  window.addEventListener('resize', handleResize)
  // 初始化时发送折叠状态
  emit('collapse-change', isCollapsed.value)
  
  // 获取最近练习数据
  fetchRecentExercises()
  
  // 定期刷新最近练习数据（每5分钟刷新一次）
  const refreshInterval = setInterval(() => {
    fetchRecentExercises()
  }, 5 * 60 * 1000)
  
  // 保存定时器ID，以便在组件卸载时清除
  refreshIntervalId.value = refreshInterval
})

// 在组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  // 清除定时器
  if (refreshIntervalId.value) {
    clearInterval(refreshIntervalId.value)
  }
})

// 处理窗口大小变化
const handleResize = () => {
  if (window.innerWidth <= 768) {
    isCollapsed.value = true
  } else {
    isCollapsed.value = false
  }
}

// 背景设置状态
const backgroundType = ref('gradient')
const backgroundColor = ref('rgba(107, 70, 193, 0.8)')
const gradientType = ref('linear')
const gradientDirection = ref('to bottom right')
const gradientColorStart = ref('rgba(107, 70, 193, 0.8)')
const gradientColorEnd = ref('rgba(72, 41, 178, 0.8)')
const backgroundImage = ref('')
const customImageUrl = ref('')
const localImagePreview = ref('')
const localImageFile = ref(null)
const opacity = ref(0.9)
const radialShape = ref('circle')
const radialPosition = ref('center')
const imageCategory = ref('all')

// 预设图片
const presetImages = [
  { url: '/backgrounds/bg1.jpg', category: 'nature' },
  { url: '/backgrounds/bg2.jpg', category: 'nature' },
  { url: '/backgrounds/bg3.jpg', category: 'abstract' },
  { url: '/backgrounds/bg4.jpg', category: 'abstract' },
  { url: '/backgrounds/abstract1.jpg', category: 'abstract' },
  { url: '/backgrounds/nature1.jpg', category: 'nature' },
  { url: '/backgrounds/city1.jpg', category: 'city' },
  { url: '/backgrounds/tech1.jpg', category: 'tech' },
]

// 根据分类筛选图片
const filteredImages = computed(() => {
  if (imageCategory.value === 'all') {
    return presetImages
  } else {
    return presetImages.filter(image => image.category === imageCategory.value)
  }
})

// 预设主题
const presetThemes = [
  { type: 'gradient', gradientType: 'linear', direction: 'to bottom right', colorStart: 'rgba(107, 70, 193, 0.8)', colorEnd: 'rgba(72, 41, 178, 0.8)' },
  { type: 'gradient', gradientType: 'linear', direction: 'to right', colorStart: 'rgba(16, 185, 129, 0.8)', colorEnd: 'rgba(5, 150, 105, 0.8)' },
  { type: 'gradient', gradientType: 'linear', direction: 'to bottom', colorStart: 'rgba(239, 68, 68, 0.8)', colorEnd: 'rgba(153, 27, 27, 0.8)' },
  { type: 'gradient', gradientType: 'radial', colorStart: 'rgba(59, 130, 246, 0.8)', colorEnd: 'rgba(29, 78, 216, 0.8)' },
  { type: 'gradient', gradientType: 'linear', direction: 'to bottom right', colorStart: 'rgba(236, 72, 153, 0.8)', colorEnd: 'rgba(159, 18, 57, 0.8)' },
  { type: 'gradient', gradientType: 'linear', direction: 'to right', colorStart: 'rgba(245, 158, 11, 0.8)', colorEnd: 'rgba(180, 83, 9, 0.8)' },
  { type: 'gradient', gradientType: 'linear', direction: '135deg', colorStart: 'rgba(55, 65, 81, 0.8)', colorEnd: 'rgba(17, 24, 39, 0.8)' },
  { type: 'gradient', gradientType: 'linear', direction: '45deg', colorStart: 'rgba(124, 58, 237, 0.8)', colorEnd: 'rgba(79, 70, 229, 0.8)' },
  { type: 'solid', color: 'rgba(17, 24, 39, 0.9)' },
  { type: 'solid', color: 'rgba(107, 70, 193, 0.8)' },
  { type: 'solid', color: 'rgba(16, 185, 129, 0.8)' },
  { type: 'solid', color: 'rgba(239, 68, 68, 0.8)' }
]

// 获取预设主题样式
const getPresetThemeStyle = (theme) => {
  if (theme.type === 'solid') {
    return {
      backgroundColor: theme.color,
    }
  } else if (theme.type === 'gradient') {
    if (theme.gradientType === 'linear') {
      return {
        background: `linear-gradient(${theme.direction}, ${theme.colorStart}, ${theme.colorEnd})`,
      }
    } else {
      return {
        background: `radial-gradient(circle, ${theme.colorStart}, ${theme.colorEnd})`,
      }
    }
  }
  
  return {}
}

// 应用预设主题
const applyPresetTheme = (theme) => {
  backgroundType.value = theme.type
  
  if (theme.type === 'solid') {
    backgroundColor.value = theme.color
  } else if (theme.type === 'gradient') {
    gradientType.value = theme.gradientType
    if (theme.gradientType === 'linear') {
      gradientDirection.value = theme.direction
    }
    gradientColorStart.value = theme.colorStart
    gradientColorEnd.value = theme.colorEnd
  }
}

// 应用自定义图片
const applyCustomImage = () => {
  if (customImageUrl.value && customImageUrl.value.trim() !== '') {
    backgroundImage.value = customImageUrl.value.trim()
    ElMessage.success('自定义背景图片已应用')
  } else {
    ElMessage.warning('请输入有效的图片URL')
  }
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.error('图片预览加载失败', e)
  ElMessage.error('图片预览加载失败')
  localImagePreview.value = ''
}

// 处理本地图片选择
const handleLocalImageChange = (file) => {
  if (!file) {
    ElMessage.warning('未选择图片文件')
    return
  }
  
  console.log('选择了图片文件:', file.name, file.type, Math.round(file.size / 1024) + 'KB')
  localImageFile.value = file.raw
  
  // 创建预览并压缩图片
  compressImage(file.raw, (compressedDataUrl) => {
    localImagePreview.value = compressedDataUrl
    console.log('图片预览已生成', compressedDataUrl.substring(0, 50) + '...')
    
    // 测试预览图片是否有效
    const testImg = new Image()
    testImg.onload = () => console.log('预览图片加载成功')
    testImg.onerror = () => console.error('预览图片加载失败')
    testImg.src = compressedDataUrl
  })
}

// 压缩图片
const compressImage = (file, callback) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    console.log('文件读取成功')
    const img = new Image()
    img.onload = () => {
      console.log('原始图片尺寸:', img.width, 'x', img.height)
      
      // 创建canvas进行压缩
      const canvas = document.createElement('canvas')
      let width = img.width
      let height = img.height
      
      // 计算压缩比例，最大尺寸为800px
      const maxSize = 800
      if (width > maxSize || height > maxSize) {
        if (width > height) {
          height = Math.round((height * maxSize) / width)
          width = maxSize
        } else {
          width = Math.round((width * maxSize) / height)
          height = maxSize
        }
      }
      
      console.log('压缩后图片尺寸:', width, 'x', height)
      
      canvas.width = width
      canvas.height = height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, width, height)
      
      try {
        // 转换为base64，使用较低的质量
        const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.6)
        console.log('压缩后图片大小约:', Math.round(compressedDataUrl.length * 0.75 / 1024) + 'KB')
        callback(compressedDataUrl)
      } catch (error) {
        console.error('转换图片失败', error)
        ElMessage.error('转换图片失败')
      }
    }
    img.onerror = (error) => {
      console.error('图片加载失败', error)
      ElMessage.error('图片加载失败')
    }
    img.src = e.target.result
  }
  reader.onerror = (e) => {
    console.error('图片读取失败', e)
    ElMessage.error('图片读取失败')
  }
  
  try {
    reader.readAsDataURL(file)
  } catch (error) {
    console.error('读取图片文件失败', error)
    ElMessage.error('读取图片文件失败')
  }
}

// 应用本地图片
const applyLocalImage = () => {
  if (!localImagePreview.value) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  try {
    // 测试图片是否有效
    testImageValidity(localImagePreview.value, () => {
      // 图片有效，应用它
      backgroundImage.value = localImagePreview.value
      backgroundType.value = 'image'
      ElMessage.success('本地背景图片已应用')
      
      // 调试信息
      console.log('应用本地图片', localImagePreview.value.substring(0, 50) + '...')
    })
  } catch (error) {
    console.error('应用本地图片失败', error)
    ElMessage.error('应用本地图片失败')
  }
}

// 测试图片有效性
const testImageValidity = (imageUrl, onSuccess) => {
  console.log('测试图片有效性')
  const testImg = new Image()
  
  // 设置超时
  const timeout = setTimeout(() => {
    console.warn('图片加载超时')
    ElMessage.warning('图片加载超时，可能是图片太大')
    if (typeof onSuccess === 'function') {
      onSuccess() // 仍然尝试应用
    }
  }, 3000)
  
  testImg.onload = () => {
    clearTimeout(timeout)
    console.log('图片测试成功 - 尺寸:', testImg.width, 'x', testImg.height)
    if (typeof onSuccess === 'function') {
      onSuccess()
    }
  }
  
  testImg.onerror = (error) => {
    clearTimeout(timeout)
    console.error('图片测试失败', error)
    ElMessage.error('图片无效，请重新选择')
    // 清除预览
    localImagePreview.value = ''
  }
  
  testImg.src = imageUrl
}

// 图片上传前的验证
const beforeLocalImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  return true
}

// 取消本地图片
const cancelLocalImage = () => {
  localImagePreview.value = ''
  localImageFile.value = null
}

// 保存设置到数据库
const saveSettings = async () => {
  try {
    // 检查是否使用本地图片
    if (backgroundType.value === 'image' && backgroundImage.value.startsWith('data:image/')) {
      console.log('保存本地图片设置', backgroundImage.value.substring(0, 50) + '...')
      
      // 检查图片大小
      const imageSize = Math.round(backgroundImage.value.length * 0.75 / 1024)
      console.log(`图片大小约 ${imageSize}KB`)
      
      if (imageSize > 2048) {
        ElMessage.warning(`图片较大(${imageSize}KB)，可能影响性能，建议使用更小的图片`)
      }
    }
    
    const settings = {
      backgroundType: backgroundType.value,
      backgroundColor: backgroundColor.value,
      gradientType: gradientType.value,
      gradientDirection: gradientDirection.value,
      gradientColorStart: gradientColorStart.value,
      gradientColorEnd: gradientColorEnd.value,
      backgroundImage: backgroundImage.value,
      opacity: opacity.value,
      radialShape: radialShape.value,
      radialPosition: radialPosition.value,
    }
    
    try {
      // 尝试使用API保存
      console.log('尝试通过API保存背景设置')
      await axios.post('/api/settings/background/', settings)
      ElMessage.success('背景设置已保存')
    } catch (apiError) {
      // API不存在，使用本地存储
      console.log('API不可用，使用本地存储保存背景设置')
      
      try {
        // 检查是否有大型base64图片
        if (backgroundType.value === 'image' && backgroundImage.value.startsWith('data:image/')) {
          const imageSize = Math.round(backgroundImage.value.length * 0.75 / 1024)
          
          // 如果图片太大，尝试进一步压缩
          if (imageSize > 1024) {
            console.log('图片较大，尝试进一步压缩')
            
            // 创建一个临时图片元素
            const img = new Image()
            img.onload = () => {
              try {
                // 创建canvas进行压缩
                const canvas = document.createElement('canvas')
                const maxSize = 600 // 更小的尺寸
                let width = img.width
                let height = img.height
                
                if (width > height) {
                  height = Math.round((height * maxSize) / width)
                  width = maxSize
                } else {
                  width = Math.round((width * maxSize) / height)
                  height = maxSize
                }
                
                canvas.width = width
                canvas.height = height
                const ctx = canvas.getContext('2d')
                ctx.drawImage(img, 0, 0, width, height)
                
                // 使用更低的质量
                const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.5)
                const newSize = Math.round(compressedDataUrl.length * 0.75 / 1024)
                console.log(`压缩后图片大小: ${newSize}KB`)
                
                // 更新设置并保存
                settings.backgroundImage = compressedDataUrl
                
                try {
                  localStorage.setItem('background_settings', JSON.stringify(settings))
                  console.log('背景设置已保存到本地存储')
                  ElMessage.success(`背景设置已保存到本地 (图片已压缩至${newSize}KB)`)
                  
                  // 通知Background组件更新
                  window.dispatchEvent(new CustomEvent('background-settings-updated'))
                  console.log('已发送背景设置更新事件')
                  
                  showBackgroundSettings.value = false
                } catch (storageError) {
                  console.error('保存到本地存储失败', storageError)
                  fallbackSave(settings)
                }
              } catch (compressError) {
                console.error('压缩图片失败', compressError)
                fallbackSave(settings)
              }
            }
            
            img.onerror = () => {
              console.error('加载图片失败，无法压缩')
              fallbackSave(settings)
            }
            
            img.src = backgroundImage.value
            return // 提前返回，等待异步压缩完成
          }
        }
        
        // 直接保存
        try {
          localStorage.setItem('background_settings', JSON.stringify(settings))
          console.log('背景设置已直接保存到本地存储')
          ElMessage.success('背景设置已保存到本地')
          
          // 通知Background组件更新
          window.dispatchEvent(new CustomEvent('background-settings-updated'))
          console.log('已发送背景设置更新事件')
          
          showBackgroundSettings.value = false
        } catch (storageError) {
          console.error('本地存储失败', storageError)
          ElMessage.error('本地存储失败，图片可能太大')
          
          // 尝试移除图片后保存
          fallbackSave(settings)
        }
      } catch (error) {
        console.error('保存过程中出错', error)
        fallbackSave(settings)
      }
    }
  } catch (error) {
    console.log('加载背景设置失败，使用默认设置')
    // 使用默认设置，不抛出错误
    applyPresetTheme(presetThemes[0])
  }
}

// 回退保存方法 - 移除图片后保存
const fallbackSave = (settings) => {
  try {
    const fallbackSettings = { ...settings, backgroundImage: '' }
    localStorage.setItem('background_settings', JSON.stringify(fallbackSettings))
    ElMessage.warning('已保存设置但移除了图片，请尝试使用更小的图片')
    
    // 通知Background组件更新
    window.dispatchEvent(new CustomEvent('background-settings-updated'))
  } catch (error) {
    console.error('回退保存失败', error)
    ElMessage.error('无法保存设置')
  }
}

// 重置设置
const resetSettings = () => {
  backgroundType.value = 'gradient'
  backgroundColor.value = 'rgba(107, 70, 193, 0.8)'
  gradientType.value = 'linear'
  gradientDirection.value = 'to bottom right'
  gradientColorStart.value = 'rgba(107, 70, 193, 0.8)'
  gradientColorEnd.value = 'rgba(72, 41, 178, 0.8)'
  backgroundImage.value = ''
  customImageUrl.value = ''
  localImagePreview.value = ''
  localImageFile.value = null
  opacity.value = 0.9
  radialShape.value = 'circle'
  radialPosition.value = 'center'
  imageCategory.value = 'all'
}

// 从数据库加载设置
const loadSettings = async () => {
  try {
    // 尝试从API加载
    try {
      const response = await axios.get('/api/settings/background/')
      if (response.data) {
        const settings = response.data
        backgroundType.value = settings.backgroundType || 'gradient'
        backgroundColor.value = settings.backgroundColor || 'rgba(107, 70, 193, 0.8)'
        gradientType.value = settings.gradientType || 'linear'
        gradientDirection.value = settings.gradientDirection || 'to bottom right'
        gradientColorStart.value = settings.gradientColorStart || 'rgba(107, 70, 193, 0.8)'
        gradientColorEnd.value = settings.gradientColorEnd || 'rgba(72, 41, 178, 0.8)'
        backgroundImage.value = settings.backgroundImage || ''
        customImageUrl.value = settings.backgroundImage || ''
        opacity.value = settings.opacity !== undefined ? settings.opacity : 0.9
        radialShape.value = settings.radialShape || 'circle'
        radialPosition.value = settings.radialPosition || 'center'
        
        // 如果是预设图片，设置正确的分类
        if (backgroundType.value === 'image' && backgroundImage.value) {
          setImageCategory(backgroundImage.value)
        }
      }
    } catch (apiError) {
      // API不存在，使用本地存储，不输出警告
      console.log('使用本地存储加载背景设置')
      // 尝试从localStorage加载
      const savedSettings = localStorage.getItem('background_settings')
      if (savedSettings) {
        try {
          const settings = JSON.parse(savedSettings)
          backgroundType.value = settings.backgroundType || 'gradient'
          backgroundColor.value = settings.backgroundColor || 'rgba(107, 70, 193, 0.8)'
          gradientType.value = settings.gradientType || 'linear'
          gradientDirection.value = settings.gradientDirection || 'to bottom right'
          gradientColorStart.value = settings.gradientColorStart || 'rgba(107, 70, 193, 0.8)'
          gradientColorEnd.value = settings.gradientColorEnd || 'rgba(72, 41, 178, 0.8)'
          backgroundImage.value = settings.backgroundImage || ''
          customImageUrl.value = settings.backgroundImage || ''
          opacity.value = settings.opacity !== undefined ? settings.opacity : 0.9
          radialShape.value = settings.radialShape || 'circle'
          radialPosition.value = settings.radialPosition || 'center'
          
          // 如果是预设图片，设置正确的分类
          if (backgroundType.value === 'image' && backgroundImage.value) {
            setImageCategory(backgroundImage.value)
          }
        } catch (parseError) {
          console.log('解析本地存储的背景设置失败，使用默认设置')
          applyPresetTheme(presetThemes[0])
        }
      } else {
        // 没有本地存储，使用默认设置
        applyPresetTheme(presetThemes[0])
      }
    }
  } catch (error) {
    console.log('加载背景设置失败，使用默认设置')
    // 使用默认设置，不抛出错误
    applyPresetTheme(presetThemes[0])
  }
}

// 根据图片URL设置正确的分类
const setImageCategory = (imageUrl) => {
  const foundImage = presetImages.find(image => image.url === imageUrl)
  if (foundImage) {
    imageCategory.value = foundImage.category
  } else {
    imageCategory.value = 'all'
  }
}

// 光标设置状态
const cursorColor = ref('rgba(255, 255, 255, 1)')
const cursorSize = ref(1)

// 预设光标颜色
const presetCursorColors = [
  'rgba(255, 255, 255, 1)',
  'rgba(107, 70, 193, 1)',
  'rgba(16, 185, 129, 1)',
  'rgba(239, 68, 68, 1)',
  'rgba(59, 130, 246, 1)',
  'rgba(236, 72, 153, 1)',
  'rgba(245, 158, 11, 1)',
  'rgba(124, 58, 237, 1)',
  'rgba(255, 255, 0, 1)',
  'rgba(0, 255, 255, 1)',
  'rgba(255, 0, 255, 1)',
  'rgba(0, 255, 0, 1)'
]

// 保存光标设置
const saveCursorSettings = () => {
  try {
    const settings = {
      cursorColor: cursorColor.value,
      cursorSize: cursorSize.value
    }
    
    // 保存到本地存储
    localStorage.setItem('cursor_settings', JSON.stringify(settings))
    
    // 通知CustomCursor组件更新
    window.dispatchEvent(new CustomEvent('cursor-settings-updated', { 
      detail: settings 
    }))
    
    ElMessage.success('光标设置已保存')
    showCursorSettings.value = false
  } catch (error) {
    console.log('保存光标设置失败')
    ElMessage.error('保存光标设置失败')
  }
}

// 重置光标设置
const resetCursorSettings = () => {
  cursorColor.value = 'rgba(255, 255, 255, 1)'
  cursorSize.value = 1
}

// 加载光标设置
const loadCursorSettings = () => {
  try {
    const savedSettings = localStorage.getItem('cursor_settings')
    if (savedSettings) {
      const settings = JSON.parse(savedSettings)
      cursorColor.value = settings.cursorColor || 'rgba(255, 255, 255, 1)'
      cursorSize.value = settings.cursorSize || 1
    }
  } catch (error) {
    console.log('加载光标设置失败')
    resetCursorSettings()
  }
}

// 测试本地存储
const testLocalStorage = () => {
  try {
    // 测试写入
    localStorage.setItem('test_key', 'test_value')
    console.log('localStorage写入测试成功')
    
    // 测试读取
    const testValue = localStorage.getItem('test_key')
    console.log('localStorage读取测试:', testValue)
    
    // 测试删除
    localStorage.removeItem('test_key')
    console.log('localStorage删除测试成功')
    
    // 测试背景设置
    const savedSettings = localStorage.getItem('background_settings')
    console.log('当前背景设置:', savedSettings ? JSON.parse(savedSettings) : '无')
    
    ElMessage.success('本地存储测试成功')
  } catch (error) {
    console.error('本地存储测试失败:', error)
    ElMessage.error('本地存储测试失败: ' + error.message)
  }
}

// 处理背景设置更新
const handleBackgroundSettingsUpdated = () => {
  ElMessage.success('背景设置已更新')
}

// 在script setup部分添加isDevelopment计算属性
const isDevelopment = computed(() => process.env.NODE_ENV === 'development');

</script>

<style scoped>
.sidebar {
  height: 100vh;
  width: 240px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  overflow: hidden;
}

.sidebar.collapsed {
  width: 64px;
}

/* 移动端样式 */
.sidebar.mobile {
  transform: translateX(-100%);
  width: 240px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}

.sidebar.mobile.visible {
  transform: translateX(0);
}

.mobile-menu-button {
  position: fixed;
  top: 10px;
  left: 10px;
  z-index: 1001;
  background: rgba(107, 70, 193, 0.8);
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.mobile-menu-button:hover {
  background: var(--el-color-primary);
  transform: scale(1.05);
}

.mobile-menu-button .el-icon {
  font-size: 24px;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 28px;
  color: var(--el-color-primary);
}

.logo-text {
  font-size: 20px;
  font-weight: 700;
  color: black;
  white-space: nowrap;
  font-family: "KaiTi", "楷体", serif;
}

.collapse-icon {
  cursor: pointer;
  font-size: 20px;
  color: rgba(0, 0, 0, 0.7);
  transition: all 0.3s ease;
}

.collapse-icon:hover {
  color: black;
  transform: scale(1.1);
}

.sidebar-menu {
  flex: 1;
  border: none;
  background: transparent;
  font-family: "KaiTi", "楷体", serif;
  font-size: 18px;
  font-weight: 600;
}

/* 菜单样式 */
:deep(.el-menu) {
  border-right: none;
  background: transparent;
  font-family: "KaiTi", "楷体", serif;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  color: var(--text-color-primary);
  font-family: "KaiTi", "楷体", serif;
  font-size: 18px;
  font-weight: 600;
  height: 50px;
  line-height: 50px;
}

/* 子菜单样式 */
:deep(.el-menu--inline) {
  padding-left: 8px;
}

:deep(.el-sub-menu .el-menu-item) {
  font-size: 16px;
  height: 45px;
  line-height: 45px;
  font-weight: 500;
  padding-left: 40px !important;
}

:deep(.el-sub-menu__title) {
  padding-left: 16px !important;
}

:deep(.el-menu-item) {
  padding-left: 16px !important;
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background-color: rgba(0, 0, 0, 0.1);
}

:deep(.el-menu-item.is-active) {
  background-color: rgba(107, 70, 193, 0.2);
  color: var(--el-color-primary);
}

:deep(.el-menu-item .el-icon),
:deep(.el-sub-menu__title .el-icon) {
  font-size: 22px;
}

.sidebar-footer {
  height: 50px;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 20px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.7);
  transition: all 0.3s ease;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  font-size: 18px;
  font-weight: 600;
}

.sidebar-footer:hover {
  color: black;
  background: rgba(0, 0, 0, 0.1);
}

.notification-badge {
  margin-left: 10px;
  transform: scale(1.2);
}

:deep(.el-badge__content) {
  font-size: 14px;
  height: 22px;
  line-height: 22px;
  padding: 0 8px;
  font-weight: bold;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .sidebar {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  }
}

/* 背景设置样式 */
.background-settings-content {
  padding: 10px;
}

.setting-group {
  margin-bottom: 20px;
}

.setting-label {
  margin-bottom: 8px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.preset-themes {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-top: 10px;
}

.preset-theme {
  height: 40px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.preset-theme:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.preset-theme.active {
  border-color: #fff;
}

.preset-images {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-top: 10px;
  max-height: 240px;
  overflow-y: auto;
  padding-right: 5px;
}

.preset-image {
  height: 60px;
  border-radius: 6px;
  background-size: cover;
  background-position: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.preset-image:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.preset-image.active {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px rgba(107, 70, 193, 0.3);
}

.image-url-input {
  margin-top: 15px;
}

.setting-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.image-categories {
  margin-bottom: 10px;
}

.upload-local-image {
  margin: 15px 0;
}

.upload-trigger {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-tip {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.local-image-preview {
  margin-top: 10px;
  border-radius: 6px;
  overflow: hidden;
  background: rgba(0, 0, 0, 0.2);
  padding: 5px;
}

.local-image-preview img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
  display: block; /* 确保图片正确显示 */
}

.preview-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
}

/* 光标设置样式 */
.cursor-settings-content {
  padding: 10px;
}

.preset-colors {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-top: 10px;
}

.preset-color {
  height: 30px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.preset-color:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.preset-color.active {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px rgba(107, 70, 193, 0.3);
}

/* 调试面板样式 */
.debug-panel {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 16px;
  font-size: 12px;
  border: 1px dashed rgba(255, 255, 255, 0.2);
}

.debug-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: var(--el-color-warning);
}

.debug-button {
  background: var(--el-color-primary);
  border: none;
  color: white;
  padding: 5px 10px;
  margin-top: 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.debug-button:hover {
  background: var(--el-color-primary-light-3);
}

/* 新增样式 */
.recent-items-container,
.favorite-items-container {
  max-height: 300px;
  overflow-y: auto;
}

.remove-favorite {
  position: absolute;
  right: 10px;
  color: var(--el-color-danger);
  font-size: 14px;
  opacity: 0;
  transition: opacity 0.3s;
}

:deep(.el-menu-item:hover) .remove-favorite {
  opacity: 1;
}

.favorite-badge {
  margin-left: 8px;
}

:deep(.el-badge__content) {
  transform: scale(0.8);
}

/* 新增样式 */
.favorite-manager-content {
  padding: 0 10px;
}

.favorite-manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.favorite-manager-header h3 {
  margin: 0;
}

.export-option-item,
.import-option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.export-option-item .el-icon,
.import-option-item .el-icon {
  margin-left: 8px;
  color: var(--el-color-info);
  cursor: help;
}

.export-format,
.file-upload-section {
  margin-top: 20px;
}

.search-options {
  margin: 15px 0;
}

.search-results h3 {
  margin-top: 20px;
  margin-bottom: 10px;
}

.search-result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-result-item:hover {
  background-color: rgba(255, 255, 255, 0.05);
}

.result-info {
  flex: 1;
}

.result-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.result-description {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

/* 自定义对话框样式 */
:deep(.custom-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.custom-dialog .el-dialog__header) {
  background-color: #ffffff;
  margin: 0;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.custom-dialog .el-dialog__body) {
  background-color: #ffffff;
  color: #333;
  padding: 20px;
}

:deep(.custom-dialog .el-dialog__footer) {
  background-color: #ffffff;
  border-top: 1px solid #f0f0f0;
  padding: 10px 20px;
}

:deep(.custom-dialog .el-checkbox__label) {
  color: #333;
}

:deep(.custom-dialog .search-result-item:hover) {
  background-color: #f5f7fa;
}

:deep(.custom-dialog .result-title) {
  color: #333;
}

:deep(.custom-dialog .result-description) {
  color: #666;
}

:deep(.custom-dialog .el-tabs__item) {
  color: #333;
}

:deep(.custom-dialog .el-tabs__item.is-active) {
  color: var(--el-color-primary);
}

:deep(.custom-dialog .el-tabs__nav-wrap::after) {
  background-color: #e4e7ed;
}

.recent-exercise-item {
  display: flex !important;
  align-items: center !important;
  justify-content: space-between !important;
  padding-right: 20px !important;
}

.recent-exercise-title {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 8px;
}

.recent-exercise-count {
  flex-shrink: 0;
}

.loading-exercises {
  padding: 8px 20px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.featured-exercise {
  position: relative;
  background-color: rgba(103, 194, 58, 0.1);
  border-left: 3px solid var(--el-color-success);
  margin: 5px 10px;
  border-radius: 4px;
}

.featured-exercise:hover {
  background-color: rgba(103, 194, 58, 0.2);
}

.featured-tag {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.featured-parser {
  position: relative;
  background-color: rgba(64, 158, 255, 0.1);
  border-left: 3px solid var(--el-color-primary);
  margin: 5px 10px;
  border-radius: 4px;
}

.featured-parser:hover {
  background-color: rgba(64, 158, 255, 0.2);
}

.exercise-mode-item {
  position: relative;
  margin: 5px 10px;
  border-radius: 4px;
}

.mode-tag {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}
</style>